const { Users } = require("../db/mongodb");
const router =require("koa-router")();

//增
router.post('/addtion',async(ctx) => {
    const { name, age, sex,address,tel } = ctx.request.body;
    const user = new Users({
        name,
        age,
        sex,
        address,
        tel,
    });
    //save方法是异步的，必须等待它执行完成后才能ctx.body，否则，ctx.body是无法返回到页面的
    const isSuccess = await user.save()
        .then( () => {
            return true
        })
        .catch( err => {
            console.log(err);
            return false
        });
    ctx.body = isSuccess ? {status:200,msg:"添加成功"} : {status:400,msg:"添加失败"}
});

//删
router.get('/deletion',async ctx => {
    const res = ctx.request.body;
    const { name } = res;
    if(name) {
        // 根据id删除数据
        await Users.deleteOne({ name: name });
        ctx.body = {
            status: 200,
            msg:"删除成功"
        };
    }
});

//改
router.get('/modification',async ctx => {
    const res = ctx.request.body;
    const { name } = res;
    if(name) {
        // 更新单条数据
        await Users.updateOne({ name: name }, { $set:ctx.request.body });
        ctx.body = {
            status: 200,
            msg:"更新成功"
        };
    }
});

//查
router.get('/locating',async ctx => {
    const result = await Users.find(ctx.query).then( res => {
        return res
    }).catch( (err) => {
        return err
    });
    ctx.body = {
        status:200,
        msg:"查询成功！",
        result:result
    }
});

//按条件查询
router.get('/localting',async ctx => {
    const {name}=ctx.request.body;
    const result = await Users.findOne({name:name}).then( res => {
        return res
    }).catch( (err) => {
        return err
    });
    ctx.body = {
        status:200,
        msg:"查询成功！",
        result:result
    }
});

module.exports = router;